import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../providers/font_size_provider.dart';
import '../repositories/note_repository.dart';
import '../repositories/essay_material_repository.dart';
import '../models/note.dart';
import '../models/essay_material.dart';
import '../widgets/math_formula_widget.dart';
import '../widgets/markdown_preview_widget.dart';
import 'package:go_router/go_router.dart';
import 'dart:io';
import '../widgets/image_preview_widget.dart';



class DailyMustSeeScreen extends StatefulWidget {
  const DailyMustSeeScreen({super.key});

  @override
  State<DailyMustSeeScreen> createState() => _DailyMustSeeScreenState();
}

class _DailyMustSeeScreenState extends State<DailyMustSeeScreen> with TickerProviderStateMixin {
  final NoteRepository _noteRepository = NoteRepository();
  final EssayMaterialRepository _essayMaterialRepository = EssayMaterialRepository();
  
  // 笔记数据
  List<Note> _recentNotes = [];
  List<Note> _recentlyUpdatedNotes = [];
  Map<String, List<Note>> _categoryNotes = {
    '时政': [],
    '常识判断': [],
    '言语理解与表达': [],
    '数量关系': [],
    '判断推理': [],
    '资料分析': [],
  };

  // 构建笔记内容组件，统一使用MarkdownPreviewWidget（已集成分数功能）
  Widget _buildNoteContentWidget(String content, double textScaleFactor) {
    return MarkdownPreviewWidget(
      content: content,
      style: TextStyle(
        fontSize: 16 * textScaleFactor,
        fontFamily: 'FangSong',
        color: Colors.black,
      ),
      textScaleFactor: textScaleFactor,
    );
  }

  // 检查文本中是否包含括号中的分数
  
  // 作文素材数据
  List<EssayMaterial> _recentEssayMaterials = [];
  List<String> _essayMaterialCategories = [];
  Map<String, List<EssayMaterial>> _categoryEssayMaterials = {};
  
  bool _isLoading = true;
  String? _errorMessage;
  
  // 主标签页控制器
  late TabController _mainTabController;
  final List<String> _mainTabs = ['我的笔记', '作文素材'];
  
  // 笔记子标签页控制器
  late TabController _noteTabController;
  final List<String> _noteTabs = ['时政', '常识判断', '言语理解', '数量关系', '判断推理', '资料分析']; // 缩短"言语理解与表达"为"言语理解"
  
  // 作文素材分类标签页控制器
  late TabController _essayMaterialTabController;
  List<String> _essayMaterialTabs = ['全部'];
  String _selectedEssayCategory = '全部';
  
  @override
  void initState() {
    super.initState();
    _mainTabController = TabController(length: _mainTabs.length, vsync: this);
    _noteTabController = TabController(length: _noteTabs.length, vsync: this);
    _essayMaterialTabController = TabController(length: _essayMaterialTabs.length, vsync: this);
    _loadData();
  }
  
  @override
  void dispose() {
    _mainTabController.dispose();
    _noteTabController.dispose();
    _essayMaterialTabController.dispose();
    super.dispose();
  }
  
  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    
    try {
      // 获取笔记数据
      final recentNotes = await _noteRepository.getRecentNotes(6); // 获取6条最新笔记
      final recentlyUpdatedNotes = await _noteRepository.getRecentlyUpdatedNotes(6); // 获取6条最近更新的笔记
      
      // 获取分类笔记数据
      for (final category in _categoryNotes.keys) {
        final notes = await _noteRepository.getNotesByCategory(category);
        _categoryNotes[category] = notes.take(6).toList(); // 每个分类最多显示6条
      }
      
      // 获取作文素材数据
      final recentEssayMaterials = await _essayMaterialRepository.getRecentEssayMaterials(5); // 获取5条最新作文素材
      
      // 获取作文素材分类
      final categories = await _essayMaterialRepository.getCategories();
      categories.insert(0, '全部'); // 添加"全部"选项
      
      // 为每个分类加载作文素材
      final categoryMaterials = <String, List<EssayMaterial>>{};
      categoryMaterials['全部'] = recentEssayMaterials;
      
      for (final category in categories) {
        if (category != '全部') {
          final materials = await _essayMaterialRepository.getEssayMaterialsByCategory(category);
          categoryMaterials[category] = materials.take(5).toList(); // 每个分类最多显示5条
        }
      }
      
      setState(() {
        _recentNotes = recentNotes;
        _recentlyUpdatedNotes = recentlyUpdatedNotes;
        // 分类笔记数据已在循环中设置
        _recentEssayMaterials = recentEssayMaterials;
        _essayMaterialCategories = categories;
        _categoryEssayMaterials = categoryMaterials;
        
        // 更新作文素材标签页
        _essayMaterialTabs = categories;
        _essayMaterialTabController = TabController(
          length: _essayMaterialTabs.length,
          vsync: this,
        );
        
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = '加载数据失败: $e';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final fontSizeProvider = Provider.of<FontSizeProvider>(context);
    final textScaleFactor = fontSizeProvider.fontScale;
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('每日必看', style: TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold)),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.import_export),
            onPressed: () {
              context.go('/note_essay_import_export');
            },
            tooltip: '导入导出',
          ),
        ],
        bottom: TabBar(
          controller: _mainTabController,
          tabs: _mainTabs.map((String tab) => Tab(text: tab)).toList(),
          indicatorColor: Theme.of(context).colorScheme.primary,
          labelColor: Theme.of(context).colorScheme.primary,
          unselectedLabelColor: Theme.of(context).colorScheme.onSurface,
          labelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          unselectedLabelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          padding: const EdgeInsets.symmetric(horizontal: 16.0), // 添加水平内边距
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(child: Text(_errorMessage!, style: const TextStyle(fontFamily: 'FangSong')))
              : TabBarView(
                    controller: _mainTabController,
                    children: [
                      // 笔记模块
                      _buildNotesTab(textScaleFactor),
                      
                      // 作文素材模块
                      _buildEssayMaterialsTab(textScaleFactor),
                    ],
                  ),
    );
  }
  
  Widget _buildSectionTitle(String title, IconData icon, double textScaleFactor) {
    return Row(
      children: [
        Icon(icon, color: Theme.of(context).colorScheme.primary),
        const SizedBox(width: 8),
        Text(
          title,
          style: TextStyle(
            fontSize: 18 * textScaleFactor,
            fontWeight: FontWeight.bold,
            color: Theme.of(context).colorScheme.primary,
            fontFamily: 'FangSong',
          ),
        ),
      ],
    );
  }
  
  Widget _buildNotesTab(double textScaleFactor) {
    return Column(
      children: [
        // 笔记子标签页
        TabBar(
          controller: _noteTabController,
          tabs: _noteTabs.map((String tab) => Tab(text: tab)).toList(),
          labelColor: Theme.of(context).colorScheme.primary,
          unselectedLabelColor: Theme.of(context).colorScheme.onSurface,
          labelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          unselectedLabelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          indicatorSize: TabBarIndicatorSize.label,
          isScrollable: true, // 允许标签页滚动，解决文字遮挡问题
          padding: const EdgeInsets.symmetric(horizontal: 8.0), // 添加水平内边距
        ),
        Expanded(
          child: TabBarView(
            controller: _noteTabController,
            children: [
              // 时政
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('时政', Icons.policy, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['时政'] ?? [], textScaleFactor),
                ],
              ),
              
              // 常识判断
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('常识判断', Icons.lightbulb, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['常识判断'] ?? [], textScaleFactor),
                ],
              ),
              
              // 言语理解
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('言语理解', Icons.chat, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['言语理解与表达'] ?? [], textScaleFactor),
                ],
              ),
              
              // 数量关系
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('数量关系', Icons.calculate, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['数量关系'] ?? [], textScaleFactor),
                ],
              ),
              
              // 判断推理
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('判断推理', Icons.psychology, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['判断推理'] ?? [], textScaleFactor),
                ],
              ),
              
              // 资料分析
              ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle('资料分析', Icons.analytics, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildNoteModules(_categoryNotes['资料分析'] ?? [], textScaleFactor),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }
  
  Widget _buildEssayMaterialsTab(double textScaleFactor) {
    return Column(
      children: [
        // 作文素材分类标签页
        TabBar(
          controller: _essayMaterialTabController,
          tabs: _essayMaterialTabs.map((String tab) => Tab(text: tab)).toList(),
          labelColor: Theme.of(context).colorScheme.primary,
          unselectedLabelColor: Theme.of(context).colorScheme.onSurface,
          labelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          unselectedLabelStyle: const TextStyle(fontFamily: 'FangSong', fontWeight: FontWeight.bold),
          indicatorSize: TabBarIndicatorSize.label,
          isScrollable: true, // 允许滚动，以显示更多分类
          padding: const EdgeInsets.symmetric(horizontal: 8.0), // 添加水平内边距
          onTap: (index) {
            setState(() {
              _selectedEssayCategory = _essayMaterialTabs[index];
            });
          },
        ),
        Expanded(
          child: TabBarView(
            controller: _essayMaterialTabController,
            children: _essayMaterialTabs.map((category) {
              return ListView(
                padding: const EdgeInsets.all(16.0),
                children: [
                  _buildSectionTitle(category, Icons.article, textScaleFactor),
                  const SizedBox(height: 8),
                  _buildEssayMaterialList(_categoryEssayMaterials[category] ?? [], textScaleFactor),
                ],
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
  
  Widget _buildNoteModules(List<Note> notes, double textScaleFactor) {
    // 如果没有笔记，显示提示信息
    if (notes.isEmpty) {
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Text(
              '暂无笔记内容',
              style: TextStyle(
                fontSize: 16 * textScaleFactor,
                fontWeight: FontWeight.bold,
                fontFamily: 'FangSong',
              ),
            ),
          ),
        ),
      );
    }
    
    // 直接显示所有笔记，不使用卡片限制
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: notes.length,
      itemBuilder: (context, index) {
        return _buildNoteItem(notes[index], textScaleFactor);
      },
    );
  }
  
  Widget _buildNoteItem(Note note, double textScaleFactor) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 笔记标题
          Text(
            note.title,
            style: TextStyle(
              fontSize: 18 * textScaleFactor,
              fontWeight: FontWeight.bold,
              fontFamily: 'FangSong',
            ),
          ),
          const SizedBox(height: 8),
          // 图片预览（如果有）
          if (note.imageUrl != null && note.imageUrl!.isNotEmpty)
            _buildImageWidget(note.imageUrl!, double.infinity, 200),
          const SizedBox(height: 8),
          // 使用MathFormulaWidget处理括号中的分数，如果没有分数则使用MarkdownPreviewWidget
          SizedBox(
            width: double.infinity,
            child: _buildNoteContentWidget(note.content, textScaleFactor),
          ),
          const SizedBox(height: 8),
          // 分类标签
          if (note.category.isNotEmpty)
            Chip(
              label: Text(
                note.category,
                style: TextStyle(fontSize: 12 * textScaleFactor, fontFamily: 'FangSong'),
              ),
              backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
              padding: EdgeInsets.zero,
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
          const Divider(), // 添加分隔线
        ],
      ),
    );
  }
  
  // 已删除_buildNoteCard方法，改为直接在页面上显示笔记内容
  

  
  // 已删除_buildNoteRow方法，改为使用ListView.builder直接显示笔记项目
  
  Widget _buildEssayMaterialList(List<EssayMaterial> materials, double textScaleFactor) {
    // 如果没有作文素材，显示提示信息
    if (materials.isEmpty) {
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: Text(
              '暂无作文素材',
              style: TextStyle(
                fontSize: 16 * textScaleFactor,
                fontWeight: FontWeight.bold,
                fontFamily: 'FangSong',
              ),
            ),
          ),
        ),
      );
    }
    
    return Column(
      children: materials.map((material) => 
        Padding(
          padding: const EdgeInsets.only(bottom: 8.0),
          child: _buildEssayMaterialCard(material, textScaleFactor),
        )
      ).toList(),
    );
  }
  
  // 构建图片显示组件，支持本地文件和网络图片
  Widget _buildImageWidget(String imageUrl, double width, double height) {
    return ImagePreviewWidget(
      imageUrl: imageUrl,
      width: width,
      height: height,
      fit: BoxFit.contain,
      showPath: false,
    );
  }

  Widget _buildEssayMaterialCard(EssayMaterial material, double textScaleFactor) {
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: () {
          // 可以导航到作文素材详情页
        },
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          material.title,
                          style: TextStyle(
                            fontSize: 16 * textScaleFactor,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'FangSong',
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          material.content,
                          style: TextStyle(fontSize: 14 * textScaleFactor, fontFamily: 'FangSong'),
                          // 移除最大行数限制，显示完整内容
                        ),
                      ],
                    ),
                  ),
                  if (material.imageUrl != null && material.imageUrl!.isNotEmpty) ...[  
                    const SizedBox(width: 12),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: _buildImageWidget(material.imageUrl!, 180, 180), // 增加图片尺寸到180x180
                    ),
                  ],
                ],
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  if (material.category.isNotEmpty)
                    Chip(
                      label: Text(
                        material.category,
                        style: TextStyle(fontSize: 12 * textScaleFactor, fontFamily: 'FangSong'),
                      ),
                      backgroundColor: Theme.of(context).colorScheme.surfaceVariant,
                      padding: EdgeInsets.zero,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),

                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 检查是否为Markdown表格
  bool _isMarkdownTable(String content) {
    return content.contains('|') && content.contains('---');
  }
}